package cn.gogpay.duoim.sdk.util;

import cn.gogpay.duoim.sdk.constant.ContentTypes;
import cn.gogpay.duoim.sdk.constant.SessionTypes;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Comparator;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class IMUtil {

    /**
     * 生成操作ID
     *
     * @return 操作ID
     */
    public static String genOperationID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static JSONObject parseContent(Object content) {
        String string = JSONObject.toJSONString(content);
        return JSONObject.parseObject(string);
    }

    public static cn.hutool.json.JSONObject parseJsonContent(Object content) {
        return JSONUtil.parseObj(content);
    }

    /**
     * 消息类型转换
     *
     * @param contentType 消息类型
     * @param content     消息内容
     * @return 消息
     */
    public static String switchContentType(Integer contentType, String content) {
        String message;
        switch (contentType) {
            case ContentTypes.Text:
                boolean typeJSON = JSONUtil.isTypeJSON(content);
                if (typeJSON) {
                    // 兼容3.0SDK简单消息变成JSON对象格式{"content":"你好"}
                    cn.hutool.json.JSONObject contentJSONObject = JSONUtil.parseObj(content);
                    message = contentJSONObject.getStr("content");
                } else {
                    message = content;
                }
                break;
            case ContentTypes.Picture:
                message = "[图片]";
                break;
            case ContentTypes.Voice:
                message = "[语音]";
                break;
            case ContentTypes.Video:
                message = "[视频]";
                break;
            default:
                message = "您有新的消息";
                break;
        }

        return message;
    }

    /**
     * 获取聊天会话ID
     *
     * @param sessionType 会话类型
     * @param send        发送者
     * @param recv        接收者
     * @return 聊天会话ID
     */
    public static String getChatConversationID(int sessionType, String send, String recv) {
        String conversation;
        switch (sessionType) {
            case SessionTypes.SingleChatType:
                conversation = "si_" + Stream.of(send, recv).sorted(Comparator.naturalOrder()).collect(Collectors.joining("_"));
                break;
            case SessionTypes.GroupChatType:
                conversation = "g_" + recv;
                break;
            case SessionTypes.SuperGroupChatType:
                conversation = "sg_" + recv;
                break;
            case SessionTypes.NotificationChatType:
                conversation = "sn_" + Stream.of(send, recv).sorted(Comparator.naturalOrder()).collect(Collectors.joining("_"));
                break;
            default:
                conversation = "";
        }

        return conversation;
    }
}
